package frmMantenimiento;

import cls.conexion;
import frm.frmPrincipal;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

public class frmMarcas extends javax.swing.JFrame {

    static conexion CP; // conexion con base de datos

    public frmMarcas() throws ClassNotFoundException, SQLException {
        initComponents();
        setLocationRelativeTo(null);
        noVer();
        CP = new conexion("proyecto2", "usrUTN", "12345");
        verdatos();
        
        
        
    }

  
    
    // metodo que muestras los datos de la tabla en la jtable
    public void verdatos() {
        DefaultTableModel modelo = (DefaultTableModel) tblMarca.getModel();
        Object[] fila = new Object[6];
        modelo.setRowCount(0);
        try {
            ResultSet datos = this.CP.select("*", "\"schUTN\".marca_articulo", "");
            while (datos.next()) {
                fila[0] = datos.getString(1);
                fila[1] = datos.getString(2);
                fila[2] = datos.getString(3);
                modelo.addRow(fila);
            }
        } catch (Exception e) {
            System.out.printf("Error: " + e.toString());
        }
    }

    private void limpiarRd() {
        rdNo.setSelected(false);
        rdSi.setSelected(false);
        rdNo.setEnabled(true);
        rdSi.setEnabled(true);
    }

    public void noVer() {
        jLabel1.setVisible(false);
        jLabel2.setVisible(false);
        jLabel4.setVisible(false);
        txtCodigo.setVisible(false);
        txtDesc.setVisible(false);
        rdNo.setVisible(false);
        rdSi.setVisible(false);
        btnFinalinarInsert.setVisible(false);
        btnFinalizarModif.setVisible(false);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblMarca = new javax.swing.JTable();
        btnInsertar = new javax.swing.JButton();
        btnModificar = new javax.swing.JButton();
        btnEliminar = new javax.swing.JButton();
        btnAtras = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        txtCodigo = new javax.swing.JTextField();
        txtDesc = new javax.swing.JTextField();
        btnFinalizarModif = new javax.swing.JButton();
        btnFinalinarInsert = new javax.swing.JButton();
        rdNo = new javax.swing.JRadioButton();
        jLabel4 = new javax.swing.JLabel();
        rdSi = new javax.swing.JRadioButton();

        jButton1.setText("jButton1");

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("MARCAS");
        addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                formKeyPressed(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                formKeyTyped(evt);
            }
        });

        tblMarca.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "cod_marca", "Descripcion", "Activo"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblMarca.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblMarcaMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tblMarca);
        if (tblMarca.getColumnModel().getColumnCount() > 0) {
            tblMarca.getColumnModel().getColumn(0).setResizable(false);
            tblMarca.getColumnModel().getColumn(1).setResizable(false);
            tblMarca.getColumnModel().getColumn(2).setResizable(false);
        }

        btnInsertar.setText("Insertar");
        btnInsertar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnInsertarActionPerformed(evt);
            }
        });

        btnModificar.setText("Modificar");
        btnModificar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnModificarActionPerformed(evt);
            }
        });

        btnEliminar.setText("Eliminar");
        btnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarActionPerformed(evt);
            }
        });

        btnAtras.setText("Atras");
        btnAtras.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAtrasActionPerformed(evt);
            }
        });
        btnAtras.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                btnAtrasKeyTyped(evt);
            }
        });

        jLabel1.setText("Codigo de Marca");

        jLabel2.setText("Descripcion");

        txtDesc.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtDescFocusLost(evt);
            }
        });

        btnFinalizarModif.setText("Finalizar");
        btnFinalizarModif.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnFinalizarModifActionPerformed(evt);
            }
        });

        btnFinalinarInsert.setText("Finalizar");
        btnFinalinarInsert.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnFinalinarInsertActionPerformed(evt);
            }
        });

        rdNo.setText("No");
        rdNo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rdNoActionPerformed(evt);
            }
        });
        rdNo.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                rdNoFocusLost(evt);
            }
        });

        jLabel4.setText("Activo");

        rdSi.setText("SI");
        rdSi.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rdSiActionPerformed(evt);
            }
        });
        rdSi.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                rdSiFocusLost(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(29, 29, 29)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addGap(35, 35, 35)
                                .addComponent(jLabel4)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(btnFinalinarInsert, javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(btnFinalizarModif, javax.swing.GroupLayout.Alignment.TRAILING)))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(txtDesc, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(rdSi)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(rdNo)))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(btnEliminar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(btnModificar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(btnInsertar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(btnAtras, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(23, 23, 23)
                        .addComponent(btnInsertar)
                        .addGap(29, 29, 29)
                        .addComponent(btnModificar)
                        .addGap(34, 34, 34)
                        .addComponent(btnEliminar))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 258, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(btnFinalizarModif)
                                .addComponent(btnFinalinarInsert)
                                .addComponent(jLabel4))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(jLabel1)
                                    .addComponent(jLabel2))
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(4, 4, 4)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                            .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addComponent(txtDesc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(10, 10, 10)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                            .addComponent(rdNo)
                                            .addComponent(rdSi)
                                            .addComponent(btnAtras))))))))
                .addGap(0, 0, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    // boton insert
    private void btnInsertarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnInsertarActionPerformed
        noVer();
        limpiarRd();
        limpiar();
        jLabel1.setVisible(true);
        jLabel2.setVisible(true);
        jLabel4.setVisible(true);
        txtCodigo.setVisible(true);
        txtDesc.setVisible(true);
        rdNo.setVisible(true);
        rdSi.setVisible(true);
        btnFinalinarInsert.setVisible(true);
        this.txtCodigo.requestFocus();
    }//GEN-LAST:event_btnInsertarActionPerformed

    // finaliza el insert a la base de datos
    private void btnFinalinarInsertActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFinalinarInsertActionPerformed
        try {
            if (!(this.txtCodigo.getText().charAt(0) == ' ')) {
                try {
                    String si = "";
                    if (rdSi.isSelected()) {
                        si = "S";
                    } else {
                        if (rdNo.isSelected()) {
                            si = "N";
                        }
                    }
                    boolean resultado = this.CP.insert("\"schUTN\".marca_articulo",
                            "(" + "'" + this.txtCodigo.getText() + "'"
                            + ", " + "'" + this.txtDesc.getText() + "' , " + "'"
                            + si + "' " + ");");
                } catch (Exception e) {
                    System.out.printf("Error: " + e.toString());
                }
                limpiar();
                int validar = JOptionPane.showConfirmDialog(
                        null,
                        "Deseas Realizar Otra operacion",
                        "  ",
                        JOptionPane.YES_NO_OPTION);
                if (validar == JOptionPane.YES_OPTION) {
                    verdatos();
                    limpiar();
                } else {
                    verdatos();
                    noVer();
                }
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Codigo Obligatorio");
        }
        limpiarRd();
    }

    // reestablece los datos
    private void limpiar() {
        txtCodigo.setText("");
        txtDesc.setText("");

    }//GEN-LAST:event_btnFinalinarInsertActionPerformed

    //boton que finaliza la modificacin
    private void btnFinalizarModifActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFinalizarModifActionPerformed
        String cod;
        DefaultTableModel modelo = (DefaultTableModel) tblMarca.getModel();
        int vector[] = tblMarca.getSelectedRows();
        int in = tblMarca.getSelectedRow();
        if (in == -1) {
            JOptionPane.showMessageDialog(null, "Selecione un valor valido");
        } else {
            for (int i = 0; i < vector.length; i++) {
                cod = (String) tblMarca.getValueAt(in, 0);
                try {
                    String si = "";
                    if (rdSi.isSelected()) {
                        si = "S";
                    } else {
                        if (rdNo.isSelected()) {
                            si = "N";
                        }
                    }
                    boolean resultado = this.CP.actualizar("\"schUTN\".marca_articulo",
                            " cod_marca= " + "'" + this.txtCodigo.getText() + "'"
                            + ", " + " descripcion= " + " '" + this.txtDesc.getText() + "' , "
                            + " activo= " + "'" + si + "' ", "cod_marca= " + "'" + cod + "'");
                } catch (Exception e) {
                    System.out.printf("Error: " + e.toString());
                }
            }
        }
        limpiarRd();
        verdatos();
        noVer();
    }//GEN-LAST:event_btnFinalizarModifActionPerformed

    // modificar
    private void btnModificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnModificarActionPerformed
        noVer();
limpiar();
        limpiarRd();
        txtCodigo.setVisible(true);
        txtDesc.setVisible(true);
        rdNo.setVisible(true);
        rdSi.setVisible(true);
        jLabel1.setVisible(true);
        jLabel2.setVisible(true);
        jLabel4.setVisible(true);
        btnFinalizarModif.setVisible(true);
        this.txtCodigo.requestFocus();
    }//GEN-LAST:event_btnModificarActionPerformed

    // boton que elimina un dato de la base de datos
    private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed
        noVer();
        limpiarRd();
        int validar = JOptionPane.showConfirmDialog(
                null,
                "Estas Seguro?",
                " CUIDADO",
                JOptionPane.YES_NO_OPTION);
        if (validar == JOptionPane.YES_OPTION) {
            try {
                boolean resultado = this.CP.eliminar("\"schUTN\".marca_articulo",
                        "cod_marca= " + "'" + this.txtCodigo.getText() + "'");
            } catch (Exception e) {
                System.out.printf("Error: " + e.toString());
            }
            verdatos();
        } else {
            verdatos();
            limpiar();
        }
    }//GEN-LAST:event_btnEliminarActionPerformed

    // boton que regresa a la vntana prinipal
    private void btnAtrasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAtrasActionPerformed
        setVisible(false);
        frmPrincipal atras = new frmPrincipal();
        atras.setVisible(true);
    }//GEN-LAST:event_btnAtrasActionPerformed

    // evento para selccionar los datos y ponerlos en los txt field
    private void tblMarcaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblMarcaMouseClicked

        limpiarRd();
        String cod;
        DefaultTableModel modelo = (DefaultTableModel) tblMarca.getModel();
        int vector[] = tblMarca.getSelectedRows();
        int in = tblMarca.getSelectedRow();

        cod = (String) tblMarca.getValueAt(in, 0);
        txtCodigo.setText(cod);

        cod = (String) tblMarca.getValueAt(in, 1);
        txtDesc.setText(cod);

        cod = (String) tblMarca.getValueAt(in, 2);
        if (cod.equals("S")) {
            rdSi.setSelected(true);

        } else {
            rdNo.setSelected(true);
        }

        if (rdSi.isSelected()) {
            rdNo.setEnabled(false);
        } else {
            rdNo.setEnabled(true);
        }

        if (rdNo.isSelected()) {
            rdSi.setEnabled(false);

        } else {
            rdSi.setEnabled(true);
        }
//limpiarRd();

    }//GEN-LAST:event_tblMarcaMouseClicked

    private void rdSiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rdSiActionPerformed
        if (rdSi.isSelected()) {
            rdNo.setEnabled(false);
            
              if(this.btnFinalizarModif.isEnabled()==true)
           {
               this.btnFinalizarModif.requestFocus();
           }
          
           
               if (this.btnFinalinarInsert.isEnabled()==true) {
                   
                   this.btnFinalinarInsert.requestFocus();
               }
        } else {
            rdNo.setEnabled(true);
        }
    }//GEN-LAST:event_rdSiActionPerformed

    private void rdNoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rdNoActionPerformed
        if (rdNo.isSelected()) {
            rdSi.setEnabled(false);
            
            
                 if(this.btnFinalizarModif.isEnabled()==true)
           {
               this.btnFinalizarModif.requestFocus();
           }
          
           
               if (this.btnFinalinarInsert.isEnabled()==true) {
                   
                   this.btnFinalinarInsert.requestFocus();
               }

        } else {
            rdSi.setEnabled(true);
        }
    }//GEN-LAST:event_rdNoActionPerformed

    private void rdSiFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_rdSiFocusLost
      if (rdSi.isSelected()==true) {
            rdNo.setEnabled(false);
                  if(this.btnFinalizarModif.isEnabled()==true)
           {
               this.btnFinalizarModif.requestFocus();
           }
          
           
               if (this.btnFinalinarInsert.isEnabled()==true) {
                   
                   this.btnFinalinarInsert.requestFocus();
               }
               
        } else {
            rdNo.setEnabled(true);
        }
    }//GEN-LAST:event_rdSiFocusLost

    private void rdNoFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_rdNoFocusLost
        // TODO add your handling code here:
       if (rdNo.isSelected()==true) {
            rdSi.setEnabled(false);
                  if(this.btnFinalizarModif.isEnabled()==true)
           {
               this.btnFinalizarModif.requestFocus();
           }
          
           
               if (this.btnFinalinarInsert.isEnabled()==true) {
                   
                   this.btnFinalinarInsert.requestFocus();
               }
               
        } else {
            rdSi.setEnabled(true);
        }
       
       if(rdNo.isSelected()==false&&rdSi.isSelected()==false)
       {
           this.rdSi.requestFocus();
       }
    }//GEN-LAST:event_rdNoFocusLost

    private void txtDescFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtDescFocusLost
         if (rdSi.isSelected()==false && rdNo.isSelected()==false) {
            this.rdSi.requestFocus();
        }else{
            if (rdSi.isSelected()==true) {
                rdSi.requestFocus();
            }else{
                rdNo.requestFocus();
            }
        }
    }//GEN-LAST:event_txtDescFocusLost

    private void formKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyTyped
        // TODO add your handling code here:
        
    }//GEN-LAST:event_formKeyTyped

    private void formKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyPressed
        // TODO add your handling code here:
        
          char tecla=evt.getKeyChar();
        if(tecla==KeyEvent.VK_ESCAPE)
        {
            setVisible(false);
            frmPrincipal F = new frmPrincipal();
            F.setVisible(true);
          
            
        }
        
    }//GEN-LAST:event_formKeyPressed

    private void btnAtrasKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_btnAtrasKeyTyped
        // TODO add your handling code here:
       
    }//GEN-LAST:event_btnAtrasKeyTyped

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(() -> {
            try {
                new frmMarcas().setVisible(true);
            } catch (ClassNotFoundException | SQLException ex) {
                Logger.getLogger(frmMarcas.class.getName()).log(Level.SEVERE, null, ex);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAtras;
    private javax.swing.JButton btnEliminar;
    private javax.swing.JButton btnFinalinarInsert;
    private javax.swing.JButton btnFinalizarModif;
    private javax.swing.JButton btnInsertar;
    private javax.swing.JButton btnModificar;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JRadioButton rdNo;
    private javax.swing.JRadioButton rdSi;
    private javax.swing.JTable tblMarca;
    private javax.swing.JTextField txtCodigo;
    private javax.swing.JTextField txtDesc;
    // End of variables declaration//GEN-END:variables
}
